package com.yange.accountbook.popup

import android.content.Context
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.CenterPopupView
import com.lxj.xpopup.interfaces.OnSelectListener
import com.yange.accountbook.R
import com.yange.accountbook.entity.AccountEntity
import com.yange.accountbook.entity.BooksEntity
import com.yange.accountbook.net.Api
import com.yange.accountbook.net.BaseResponse
import com.yange.accountbook.net.api.RetrofitClient
import com.yange.accountbook.net.observable.RecObserver
import com.yange.accountbook.utils.showToast
import java.util.stream.Collectors

class AddSplitPop(context: Context) : CenterPopupView(context) {


    lateinit var tvBook: TextView
    lateinit var tvAccount: TextView
    lateinit var btnSave: Button
    lateinit var editMoney: EditText
    lateinit var dismissListener: DismissListener
    var books: List<BooksEntity> = arrayListOf()
    var accounts: List<AccountEntity> = arrayListOf()
    var bookId = 0
    var accountId = 0
    var splitId = 0

    constructor(context: Context, splitId: Int, addListener: DismissListener) : this(context) {
        this.dismissListener = addListener
        this.splitId = splitId
    }

    override fun getImplLayoutId() = R.layout.pop_split_layout

    override fun onCreate() {
        super.onCreate()
        tvBook = findViewById(R.id.tv_book)
        tvAccount = findViewById(R.id.tv_account)
        editMoney = findViewById(R.id.et_money)
        btnSave = findViewById(R.id.btn_save)
        tvBook.setOnClickListener {
            getBookList()
        }
        tvBook.setOnClickListener {
            getBookList()
        }

        tvAccount.setOnClickListener {
            buildAccounts()
        }
        btnSave.setOnClickListener {

            if (bookId == 0) {
                showToast("请先选择账本")
            } else if (accountId == 0) {
                showToast("请先选择账户")
            } else if (TextUtils.isEmpty(editMoney.text)) {
                showToast("请输入金额")
            } else {
                commit()
            }

        }
    }


    private fun commit() {
        RetrofitClient.getInstance().invokePostBody(
            context, Api.SAVE_MODULE_RULE, mapOf(
                "accountId" to accountId,
                "accountName" to tvAccount.text.toString().trim(),
                "bookId" to bookId,
                "bookName" to tvBook.text.toString().trim(),
                "money" to editMoney.text.toString().trim(),
                "splitId" to splitId
            )
        ).subscribe(object : RecObserver<BaseResponse<Any>>(context, true, false) {
            override fun onSuccess(t: BaseResponse<Any>?) {
                showToast("添加成功")
                dismiss()
                dismissListener.dismiss()
            }

            override fun onFail(msg: String, code: Int) {
                showToast(msg)
            }
        })
    }


    /**
     * 获取账本详情
     */
    private fun getBookList() {
        if (books.isNotEmpty()){
            buildBooks()
            return
        }
        RetrofitClient.getInstance().invokeGet(context, Api.BOOK_LIST, mapOf())
            .subscribe(object : RecObserver<BaseResponse<List<BooksEntity>>>(context, true, false) {
                override fun onSuccess(t: BaseResponse<List<BooksEntity>>?) {
                    books = t!!.data
                    buildBooks()
                }
                override fun onFail(msg: String, code: Int) {
                }
            })
    }

    private fun buildBooks() {
        if (books.isNullOrEmpty()) {
            return
        }
        val bookNames = books.stream().map { it.name }.collect(Collectors.toList());
        XPopup.Builder(context)
            .atView(tvBook)
            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
            .asCenterList("请选择账本", bookNames.toTypedArray(),
                null, 0,
                object : OnSelectListener {
                    override fun onSelect(position: Int, text: String) {
                        tvBook.text = text
                        bookId = books[position].id
                        tvAccount.text = ""
                        accountId = 0
                        getAccountList()
                    }
                })
            .show()
    }


    /**
     * 获取账本详情
     */
    private fun getAccountList() {
        RetrofitClient.getInstance().invokePostBody(context, Api.ACCOUNT_LIST, mapOf( "bookId" to bookId))
            .subscribe(object : RecObserver<BaseResponse<List<AccountEntity>>>(context, true, false) {
                override fun onSuccess(t: BaseResponse<List<AccountEntity>>?) {
                    accounts = t!!.data
                    buildAccounts()
                }
                override fun onFail(msg: String, code: Int) {
                }
            })
    }

    private fun buildAccounts() {
        if (accounts.isNullOrEmpty()) {
            return
        }
        val accountNames = accounts.stream().map { it.name }.collect(Collectors.toList());
        XPopup.Builder(context)
            .atView(tvAccount)
            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
            .asCenterList("请选择账户", accountNames.toTypedArray(),
                null, 0,
                object : OnSelectListener {
                    override fun onSelect(position: Int, text: String) {
                        tvAccount.text = text
                        accountId = accounts[position].id
                    }
                })
            .show()
    }

    interface DismissListener {
        fun dismiss()
    }


}